package cn.tedu.bootdemo.security;

import cn.tedu.bootdemo.mapper.AdminMapper;
import cn.tedu.bootdemo.vo.AdminLoginVO;
import cn.tedu.bootdemo.vo.PermissionSimpleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserDetailServiceImp implements UserDetailsService {
    @Autowired
    private AdminMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        log.debug("尝试登录,用户名为{}",s);
        AdminLoginVO admin = mapper.getLonginInfoByUsername(s);
        log.debug("查询到用户信息,信息为{}",admin);
        if (admin == null) {
            throw new BadCredentialsException( "用户名不存在");
        }
        List<PermissionSimpleVO> permissions = admin.getPermissions();
        log.debug("此用户的权限为:{}",permissions);
        List<GrantedAuthority> authorities = new ArrayList<>();
        for(PermissionSimpleVO permission:permissions){
            String permissionValue = permission.getValue();
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permissionValue);
            log.debug("此用户的权限为:{}",authority);
            authorities.add(authority);

        }
        UserDetails userDetails = User.builder()
                .username(s)
                .password(admin.getPassword())
                .disabled(admin.getIsEnable() == 0)
                .accountExpired(false)
                .accountLocked(false)
                .authorities(authorities)
                .build();
        return userDetails;
    }
}
